package com.hmdp.utils;


import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Component
@Slf4j
public class CacheClient {

    private final StringRedisTemplate stringRedisTemplate;
    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, timeUnit);
    }

    public void setWithLogicalExpireTime(String key, Object value, Long time, TimeUnit timeUnit) {
        // 封装信息
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));
        // 写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public <R, ID> R queryWithPassThrough(
            String keyPrefix, ID id,
            Class<R> type, Function<ID, R> dbFallback,
            Long time, TimeUnit timeUnit)
    {
        // 1、从redis查
        String shopKey = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(shopKey);
        // 2、判断
        if(StrUtil.isNotBlank(json)){
            return JSONUtil.toBean(json, type);
        }
        // 判断命中是否是空值
        if(json != null){
            // 返回错误信息
            return null;
        }
        // 不存在， 到数据库查
        R r = dbFallback.apply(id);
        // 还是不存在，返回错误
        if(r == null){
            // 将空值写入redis
            stringRedisTemplate.opsForValue()
                    .set(shopKey, "", time, timeUnit);
            return null;
        }
        // 存在， 写入redis
        this.set(shopKey, r, time, timeUnit);
        return r;
    }


    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    // 使用逻辑过期方式解决缓存击穿
    public <R, ID> R queryWithLogicalExpire(
            String keyPrefix, ID id,
            Class<R> type, Function<ID, R> dbFallback,
            Long time, TimeUnit timeUnit)
    {
        // 1、从redis查
        String Key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(Key);
        // 2、判断
        if(StrUtil.isBlank(json)){
            // 不存在则返回空
            return null;
        }
        // 反序列化
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject)redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 需要查看过期字段判断过期时间
        if(expireTime.isAfter(LocalDateTime.now())){
            // 未过期
            return r;
        }
        // 过期，进行 缓存重建
        // 1、取锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        // 判断取锁是否成功
        if(isLock){
            //成功则开启线程进行重建数据
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //重建缓存
                    // 先查数据库
                    R apply = dbFallback.apply(id);
                    // 再写入缓存
                    this.setWithLogicalExpireTime(Key, apply, time, timeUnit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    // 释放锁
                    unlock(lockKey);
                }
            });

        }
        //     失败就返回      返回过期商铺信息
        return r;
    }
    // 利用setnx 只在key不存在是才执行的特性模拟上锁
    private boolean tryLock(String key){
        Boolean lock = stringRedisTemplate.opsForValue()
                .setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);

        return BooleanUtil.isTrue(lock);
    }
    // 释放锁
    private void unlock(String key){

        stringRedisTemplate.delete(CACHE_SHOP_KEY + key);
    }



}
